package android.slc.mp.ui.page.photo;

import static android.provider.BaseColumns._ID;
import static android.provider.MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME;
import static android.provider.MediaStore.Images.ImageColumns.BUCKET_ID;
import static android.provider.MediaStore.MediaColumns.DATA;
import static android.provider.MediaStore.MediaColumns.DATE_MODIFIED;
import static android.provider.MediaStore.MediaColumns.DISPLAY_NAME;
import static android.provider.MediaStore.MediaColumns.SIZE;

import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.slc.ml.MediaLoader;
import android.slc.ml.callback.photo.OnPhotoLoaderOnBaseCallBack;
import android.slc.ml.utils.MediaLoaderFileUtils;
import android.slc.ml.utils.MediaLoaderUriUtils;
import android.slc.mp.R;
import android.slc.mp.SlcMp;
import android.slc.mp.po.AddPhotoItem;
import android.slc.mp.po.PhotoFolder;
import android.slc.mp.po.PhotoItem;
import android.slc.mp.po.PhotoResult;
import android.slc.mp.po.SelectEvent;
import android.slc.mp.po.i.IPhotoFolder;
import android.slc.mp.po.i.IPhotoItem;
import android.slc.mp.po.i.IPhotoResult;
import android.slc.mp.ui.SlcIMpDelegate;
import android.slc.mp.ui.page.SlcMpPagerBaseVirtualVm;
import android.slc.mp.utils.SlcMpFilePickerUtils;
import android.slc.mp.utils.SlcMpMediaBrowseUtils;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultCaller;
import androidx.activity.result.ActivityResultLauncher;
import androidx.fragment.app.FragmentActivity;
import androidx.loader.content.Loader;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by slc
 */
public class SlcMpPagerPhotoVirtualVm extends SlcMpPagerBaseVirtualVm<IPhotoResult, IPhotoFolder, IPhotoItem> {
    private final List<IPhotoItem> mHeadItem = new ArrayList<>();
    private ActivityResultLauncher<Uri> registerTakePhotoResultLauncher;

    public SlcMpPagerPhotoVirtualVm(SlcIMpDelegate mediaPickerDelegate) {
        super(SlcMp.MEDIA_TYPE_PHOTO, mediaPickerDelegate);
        mHeadItem.add(new AddPhotoItem());
    }

    public void register(ActivityResultCaller activityResultCaller) {
        registerTakePhotoResultLauncher = SlcMpFilePickerUtils.registerTakePhoto(activityResultCaller, new ActivityResultCallback<Uri>() {
            @Override
            public void onActivityResult(Uri result) {
                loadResult(result);
            }

            /**
             * 加载拍照的结果
             * @param result
             */
            private void loadResult(Uri result) {
                Cursor cursor = getMediaPickerDelegate().getContext().getContentResolver().query(result, new String[]{}, null, new String[]{}, null);
                if (cursor != null) {
                    while (cursor.moveToNext()) {
                        PhotoItem photoItem = getPhotoItemByCursor(cursor);
                        IPhotoFolder folder = getPhotoFolderByCursor(cursor);
                        if (getResult().getFolders().contains(folder)) {
                            getResult().getFolders().get(getResult().getFolders().indexOf(folder)).getItems().add(0, photoItem);
                        } else {
                            folder.setCover(photoItem.getPath());
                            folder.setCoverUri(photoItem.getUri());
                            folder.addItem(photoItem);
                            getResult().getFolders().add(folder);
                        }
                        getCurrentMediaList().add(mHeadItem.size(), photoItem);
                        getResult().getAllItemFolder().getItems().add(mHeadItem.size(), photoItem);
                    }
                    cursor.close();
                    //此处通知刷新
                    getOnDataRefreshListener();
                }
            }
        });
    }

    @Override
    public void loader(FragmentActivity fragmentActivity) {
        MediaLoader.getLoader().loadPhotos(fragmentActivity,
                new OnPhotoLoaderOnBaseCallBack<IPhotoResult>(getMediaPickerDelegate().getFilePropertyWithMediaType(getMediaType())) {
                    @Override
                    protected IPhotoResult generateResultDoInBackground(Loader<Cursor> loader, Cursor data) {
                        List<IPhotoFolder> folders = new ArrayList<>();

                        IPhotoFolder folder, allItemFolder = new PhotoFolder();

                        if (data != null) {
                            PhotoItem photoItem;
                            while (data.moveToNext()) {
                                photoItem = getPhotoItemByCursor(data);
                                folder = getPhotoFolderByCursor(data);
                                if (folders.contains(folder)) {
                                    folders.get(folders.indexOf(folder)).addItem(photoItem);
                                } else {
                                    folder.setCover(photoItem.getPath());
                                    folder.setCoverUri(photoItem.getUri());
                                    folder.addItem(photoItem);
                                    folders.add(folder);
                                }
                                allItemFolder.addItem(photoItem);
                            }
                        }

                        //添加头部item
                        allItemFolder.getItems().addAll(0, mHeadItem);
                        if (allItemFolder.getItems().size() > mHeadItem.size()) {
                            allItemFolder.setCover(allItemFolder.getItems().get(mHeadItem.size()).getPath());
                            allItemFolder.setCoverUri(allItemFolder.getItems().get(mHeadItem.size()).getUri());
                        }
                        allItemFolder.setName(SlcMp.getInstance().getApp().getString(R.string.slc_m_p_all_pictures));
                        allItemFolder.setHeadCount(mHeadItem.size());
                        folders.add(0, allItemFolder);

                        return new PhotoResult(folders);
                    }

                    @Override
                    public void onResult(IPhotoResult result) {
                        SlcMpPagerPhotoVirtualVm.this.onResult(result);
                    }

                });
    }

    /**
     * 通过游标获取PhotoItem
     *
     * @param cursor
     * @return
     */
    private PhotoItem getPhotoItemByCursor(Cursor cursor) {
        int imageId = cursor.getInt(cursor.getColumnIndexOrThrow(_ID));
        String name = cursor.getString(cursor.getColumnIndexOrThrow(DISPLAY_NAME));
        long size = cursor.getLong(cursor.getColumnIndexOrThrow(SIZE));
        String filePath = cursor.getString(cursor.getColumnIndexOrThrow(DATA));
        long modified = cursor.getLong(cursor.getColumnIndexOrThrow(DATE_MODIFIED));
        int width = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.WIDTH));
        int height = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.HEIGHT));
        PhotoItem item = new PhotoItem(imageId, name, filePath, size, modified, width, height);
        item.setUri(MediaLoaderUriUtils.id2Uri(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageId));
        item.setMediaTypeTag(getMediaType());
        item.setExtension(MediaLoaderFileUtils.getFileExtension(filePath));
        return item;
    }

    /**
     * 通过游标获取IPhotoFolder
     *
     * @param cursor
     * @return
     */
    private IPhotoFolder getPhotoFolderByCursor(Cursor cursor) {
        String folderId = cursor.getString(cursor.getColumnIndexOrThrow(BUCKET_ID));
        String folderName = cursor.getString(cursor.getColumnIndexOrThrow(BUCKET_DISPLAY_NAME));
        IPhotoFolder folder = new PhotoFolder();
        folder.setId(folderId);
        folder.setName(folderName);
        return folder;
    }

    @Override
    public void onItemClick(int position) {
        if (getCurrentMediaList().get(position) instanceof AddPhotoItem) {
            takePhoto();
        } else {
            new SlcMpMediaBrowseUtils.Builder().setCurrentPosition(position).setEdit(true)
                    .setPhoto(getCurrentMediaList().get(position)).build(getMediaPickerDelegate().getContext());
        }
    }

    @Override
    public void onItemChildClick(int position) {
        if (getCurrentMediaList().get(position) instanceof AddPhotoItem) {
            takePhoto();
        } else {
            new SlcMpMediaBrowseUtils.Builder().setCurrentPosition(position).setEdit(true)
                    .setPhoto(getCurrentMediaList().get(position)).build(getMediaPickerDelegate().getContext());
        }
    }

    /**
     * 拍照
     */
    protected void takePhoto() {
        registerTakePhotoResultLauncher.launch(MediaLoaderUriUtils.image2UriByInsert(getMediaPickerDelegate().getContext()));
    }

}
